package com.jc.service.zflservice;

import com.alibaba.fastjson.JSONObject;
import com.jc.common.util.ExceptionUtil;
import com.jc.ds.base.service.BaseServiceException;
import com.jc.ds.model.*;
import com.jc.framework.enums.*;
import com.jc.service.api.ProductCheckAdapter;
import com.jc.service.supplier.SupplierService;
import com.jc.service.suppliergoods.SupplierGoodsService;
import com.jc.service.suppliergoodspicturelist.SupplierGoodsPictureListService;
import com.jc.service.supplierproduct.SupplierProductService;
import com.jc.service.supplierproductprice.SupplierProductPriceService;
import com.jc.service.systemloglist.SystemLogListService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@SuppressWarnings("all")
@Service
public class ZflProductServiceImpl extends ProductCheckAdapter implements ZflProductService {

    @Autowired
    private SystemLogListService systemLogListService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private SupplierGoodsService supplierGoodsService;
    @Autowired
    private SupplierProductService supplierProductService;
    @Autowired
    private SupplierGoodsPictureListService supplierGoodsPictureListService;
    @Autowired
    private SupplierProductPriceService supplierProductPriceService;

    /**
     * 获取最福利产品列表
     * */
    @Override
    public Map<String,Object> queryProductList(Map<String, Object> param) throws Exception {
        if (param.get("keyword") == null){
            //关键词为空
            throw new BaseServiceException("缺少必传参数 : 搜索关键词");
        }
        if(param.get("pageIndex") == null){
            //当前页为空
            throw new BaseServiceException("缺少必传参数 : 当前页");
        }
        if(param.get("pageSize") == null){
            //当前页数为空
            throw new BaseServiceException("缺少必传参数 : 当前页数");
        }
        //加密参数请求接口
        String resultS = null;
        try{
            int keyword = toHash(param.get("keyword").toString());
            resultS = ZflCommonUtil.ZFLHttpUtil(ZFLApi.PRODUCT_LIST_METHOD_VERSION.getName(), ZFLApi.PRODUCT_LIST_METHOD_VERSION.getDesc(), param);
            systemLogListService.addSystemLog(JSONObject.toJSONString(param), Conclusion.OK, null, LogType.ZFL_GET_PRODUCT_DETAIL, resultS);
        }catch (Exception e){
            systemLogListService.addSystemLog(JSONObject.toJSONString(param), Conclusion.FAIL, ExceptionUtil.subExceptionMessage(e, 0, 150), LogType.ZFL_GET_PRODUCT_DETAIL, resultS);
            e.printStackTrace();
        }
        //请求信息写入日志

        if (StringUtils.isEmpty(resultS)){
            throw new BaseServiceException("请求最福利产品列表接口返回数据为空");
        }
        Map<String,Object> resultMap = JSONObject.parseObject(resultS, Map.class);
        if (resultMap.get("resultCode") != null && !"0".equals(resultMap.get("resultCode"))){
            throw new BaseServiceException("接口返回异常 : " + resultMap.get("resultDesc"));
        }
        if (resultMap.get("bizContent") == null){
            throw new BaseServiceException("获取最福利产品列表数据为空");
        }
        Map<String,Object> dataMap = JSONObject.parseObject(resultMap.get("bizContent").toString(), Map.class);
        System.out.println(dataMap);
        //获取到产品列表
        List<Map<String,Object>> goods = JSONObject.parseObject(JSONObject.parseObject(dataMap.get("items").toString(), Map.class).get("resultList").toString(), List.class);
        Integer size = JSONObject.parseObject(JSONObject.parseObject(dataMap.get("items").toString(), Map.class).get("totalItem").toString(), Integer.class);
        //遍历产品列表 获取产品详情
        return new HashMap<String, Object>(){{
            put("goods",goods);
            put("size",size);
        }};
    }


    /**
     * 获取最福利产品列表
     * */
    @Override
    public void getProductList(Map<String, Object> param) throws Exception {
        if (param.get("keyword") == null){
            //关键词为空
            throw new BaseServiceException("缺少必传参数 : 搜索关键词");
        }
        if(param.get("pageIndex") == null){
            //当前页为空
            throw new BaseServiceException("缺少必传参数 : 当前页");
        }
        if(param.get("pageSize") == null){
            //当前页数为空
            throw new BaseServiceException("缺少必传参数 : 当前页数");
        }
        //加密参数请求接口
        String resultS = null;
        try{
            int keyword = toHash(param.get("keyword").toString());
            resultS = ZflCommonUtil.ZFLHttpUtil(ZFLApi.PRODUCT_LIST_METHOD_VERSION.getName(), ZFLApi.PRODUCT_LIST_METHOD_VERSION.getDesc(), param);
            systemLogListService.addSystemLog(JSONObject.toJSONString(param), Conclusion.OK, null, LogType.ZFL_GET_PRODUCT_DETAIL, resultS);
        }catch (Exception e){
            systemLogListService.addSystemLog(JSONObject.toJSONString(param), Conclusion.FAIL, ExceptionUtil.subExceptionMessage(e, 0, 150), LogType.ZFL_GET_PRODUCT_DETAIL, resultS);
            e.printStackTrace();
        }
        //请求信息写入日志

        if (StringUtils.isEmpty(resultS)){
            throw new BaseServiceException("请求最福利产品列表接口返回数据为空");
        }
        Map<String,Object> resultMap = JSONObject.parseObject(resultS, Map.class);
        if (resultMap.get("resultCode") != null && !"0".equals(resultMap.get("resultCode"))){
            throw new BaseServiceException("接口返回异常 : " + resultMap.get("resultDesc"));
        }
        if (resultMap.get("bizContent") == null){
            throw new BaseServiceException("获取最福利产品列表数据为空");
        }
        Map<String,Object> dataMap = JSONObject.parseObject(resultMap.get("bizContent").toString(), Map.class);
        System.out.println(dataMap);
        //获取到产品列表
        List<Map<String,Object>> goods = JSONObject.parseObject(JSONObject.parseObject(dataMap.get("items").toString(), Map.class).get("resultList").toString(), List.class);
        //遍历产品列表 获取产品详情
        goods.forEach(good->{
            //查询详情
            productSku(good);
        });
    }


    @Transactional
    @Override
    public void productSku(Map<String,Object> good){
        //根据id获取具体的详情
        Map<String,Object> param = new HashMap<>();
        param.put("itemId",good.get("id"));
//        param.put("itemId",1130001);
        String resultStr = null;
        try {
            if (good.get("make") == null){
                resultStr = ZflCommonUtil.ZFLHttpUtil(ZFLApi.PRODUCT_DETAIL_METHOD_VERSION.getName(), ZFLApi.PRODUCT_DETAIL_METHOD_VERSION.getDesc(), param);
            }else{
                resultStr = ZflCommonUtil.ZFLHttpUtil(ZFLApi.PRODUCT_DETAIL_JD_VERSION.getName(), ZFLApi.PRODUCT_DETAIL_METHOD_VERSION.getDesc(), param);
            }
            systemLogListService.addSystemLog(JSONObject.toJSONString(param), Conclusion.OK, null, LogType.ZFL_GET_PRODUCT_DETAIL, resultStr);
        } catch (Exception e) {
            systemLogListService.addSystemLog(JSONObject.toJSONString(param), Conclusion.FAIL, ExceptionUtil.subExceptionMessage(e, 0, 150), LogType.ZFL_GET_PRODUCT_DETAIL, resultStr);
            e.printStackTrace();
        }
        Map<String,Object> proDetail = JSONObject.parseObject(JSONObject.parseObject(resultStr, Map.class).get("bizContent").toString(), Map.class);
        System.out.println("产品详情"+proDetail);
        SupplierGoods supplierGoods = packageGoods(proDetail);
        SupplierGoods supplierGoodsQuer = new SupplierGoods();
        supplierGoodsQuer.setSupplierGoodsId(proDetail.get("id").toString());
        supplierGoodsQuer.setSupplierId(supplierGoods.getSupplierId());
        List<SupplierGoods> supplierGoodsList = supplierGoodsService.queryAll(supplierGoodsQuer);
        if(CollectionUtils.isNotEmpty(supplierGoodsList)){
            //商品已存在
            return;
        }
        supplierGoodsService.add(supplierGoods,false);
        //保存图片
        List<String> images = JSONObject.parseObject(proDetail.get("images").toString(), List.class);
        images.forEach(image->{
            SupplierGoodsPictureList supplierGoodsPictureList = new SupplierGoodsPictureList();
            supplierGoodsPictureList.setGid(supplierGoods.getId());
            supplierGoodsPictureList.setImagePath(image);
            supplierGoodsPictureList.setHeight(200);
            supplierGoodsPictureList.setWidth(200);
            supplierGoodsPictureList.setImageType(1);
            supplierGoodsPictureList.setGoodsId(supplierGoods.getSupplierGoodsId());
            supplierGoodsPictureListService.add(supplierGoodsPictureList,false);
        });
        //详情图
        if (proDetail.get("detailImages") == null){
            supplierGoodsService.modify(new SupplierGoods(){{
                setId(supplierGoods.getId());
                setGoodsDescType("html");
                String desc ="";
                if (proDetail.get("introduction") != null){
                    desc = desc + proDetail.get("introduction");
                }
//                if (proDetail.get("param") != null){
//                    desc = desc + proDetail.get("param");
//                }
                if (desc.length() <= 8000){
                    setGoodsDesc(desc);
                }else{
                    setGoodsDesc(desc.substring(0,8000));
                }
            }},false);
        }else{
            List<String> detailImages = JSONObject.parseObject(proDetail.get("detailImages").toString(), List.class);
            int i = 0;
            for (String image:detailImages) {
                SupplierGoodsPictureList supplierGoodsPictureList = new SupplierGoodsPictureList();
                supplierGoodsPictureList.setGid(supplierGoods.getId());
                supplierGoodsPictureList.setImagePath(image);
                supplierGoodsPictureList.setHeight(200);
                supplierGoodsPictureList.setWidth(200);
                supplierGoodsPictureList.setImageType(2);
                supplierGoodsPictureList.setImageOrder(i);
                supplierGoodsPictureList.setGoodsId(supplierGoods.getSupplierGoodsId());
                supplierGoodsPictureListService.add(supplierGoodsPictureList,false);
                i++;
            };
        }
        //保存sku
        List<Map<String,Object>> skuVOs = JSONObject.parseObject(proDetail.get("skuVOs").toString(), List.class);
        skuVOs.forEach(sku->{
            sku.put("gid",supplierGoods.getId());
            sku.put("goodsId",supplierGoods.getSupplierGoodsId());
            sku.put("nameJd",supplierGoods.getName());
            SupplierProduct supplierProductQuer = new SupplierProduct();
            supplierProductQuer.setProductId(sku.get("id").toString());
            supplierProductQuer.setGid(supplierGoods.getId());
            List<SupplierProduct> supplierProducts = supplierProductService.queryAll(supplierProductQuer);
            SupplierProduct supplierProduct = packageObjectProduct(sku);
            if(CollectionUtils.isEmpty(supplierProducts)){
                supplierProductService.add(supplierProduct,false);
            }else{
                supplierProduct.setId(supplierProducts.get(0).getId());
                supplierProductService.modify(supplierProduct,false);
            }
            //校验属性类型
//            Boolean flag = false;
//            Boolean typeBool = checkProType(null, supplierProduct.getId(), Long.valueOf(supplierProduct.getProductId()));
//            Boolean attributeName1 = checkProAttribute(sku.get("attributeName1").toString(), supplierProduct.getId(), Long.valueOf(supplierProduct.getProductId()));
//            if (StringUtils.isNotBlank(sku.get("attributeName2").toString())){
//                checkProAttribute(sku.get("attributeName2").toString(), supplierProduct.getId(), Long.valueOf(supplierProduct.getProductId()));
//            }
//            Boolean aBoolean1 = checkProAttributeValue(sku.get("attributeName1").toString(), sku.get("attributeValue1").toString(), supplierProduct.getId(), Long.valueOf(supplierProduct.getProductId()));
//            if (StringUtils.isNotBlank(sku.get("attributeValue2").toString())){
//                checkProAttributeValue(sku.get("attributeName2").toString(), sku.get("attributeValue2").toString(), supplierProduct.getId(), Long.valueOf(supplierProduct.getProductId()));
//            }
//            if (typeBool){
//                //TODO 保存pro和属性的关系
//            }
            //保存pro和价格的关系
            SupplierProductPrice supplierProductPrice = priceCalculation(0, 0, Integer.valueOf(sku.get("price").toString()), Integer.valueOf(sku.get("originPrice").toString()), 0, supplierProduct.getId());
            SupplierProductPrice supplierProductPriceQu = new SupplierProductPrice();
            supplierProductPriceQu.setSupplierProductId(supplierProductPrice.getSupplierProductId());
            List<SupplierProductPrice> supplierProductPrices = supplierProductPriceService.queryAll(supplierProductPriceQu);
            if(supplierProductPrices != null && supplierProductPrices.size() > 0){
                return;
            }
            supplierProductPriceService.add(supplierProductPrice,false);
        });
    }

    /**
     /计算价格
     hastax 是否含税
     taxCooperatePrice 含税价
     cooperatePrice 不含税价
     salePrice 市场价
     defaultFreight 运费 默认为0
     */
    @Override
    public SupplierProductPrice priceCalculation(Integer hastax , Integer taxCooperatePrice , Integer cooperatePrice , Integer salePrice , Integer freight,Long productId){
        //0 不含税 1 含税
        SupplierProductPrice _supplierProductPrice = new SupplierProductPrice();
        //含税价 分
        _supplierProductPrice.setTaxcooperateprice(taxCooperatePrice);
        //不含税价 分
        _supplierProductPrice.setCooperateprice(cooperatePrice);
        //运费
        if (freight == null){
            freight = ProductPrice.DEFAULTSHIPPINGCOST.getName();
        }
        //成本价
        if (0 == hastax){
            _supplierProductPrice.setCostPrice(cooperatePrice + freight);
        }else{
            _supplierProductPrice.setCostPrice(taxCooperatePrice + freight);
        }
        //市场价是否为空
        if(salePrice == null){
            _supplierProductPrice.setSaleprice(_supplierProductPrice.getCostPrice()+ (1*ProductPrice.MARKETPRICEPERCENTAGE.getName()/100));
        }else{
            _supplierProductPrice.setSaleprice(salePrice);
        }
        int private_cost_price = 0;
        if (hastax == 0) {// 不含税
            private_cost_price = _supplierProductPrice.getCooperateprice()+ freight;
        } else {
            private_cost_price = _supplierProductPrice.getTaxcooperateprice() + freight;
        }
        // 求差价
        int diffPrice = (_supplierProductPrice.getSaleprice()+freight) - private_cost_price;
        if (diffPrice < 0) {
            System.out.println("严重警告 ,出现负数................................... 产品SKU ID : " + productId);
        }
        int step = diffPrice / 4; // 四个等级，每级的差价
        _supplierProductPrice.setSupplierProductId(Long.valueOf(productId));
        _supplierProductPrice.setMoneyPrice(_supplierProductPrice.getSaleprice());
        _supplierProductPrice.setLeve1Price(private_cost_price + step + step + step);
        _supplierProductPrice.setLeve2Price(private_cost_price + step + step);
        _supplierProductPrice.setLeve3Price(private_cost_price + step);
        _supplierProductPrice.setLeve4Price(private_cost_price);
        _supplierProductPrice.setUnionCostPrice(private_cost_price);
        _supplierProductPrice.setDefaultFreight(freight);
        return _supplierProductPrice;
    }


    public SupplierGoods packageGoods(Map<String,Object> param){
            SupplierGoods supplierGoods = new SupplierGoods();
            //产品名字
            supplierGoods.setName(param.get("name").toString());
            //品牌id
            if (param.get("brandId") != null){
                supplierGoods.setBrandid(Long.valueOf(param.get("brandId").toString()));
            }
            //品牌中文
            supplierGoods.setBrandnamecn(param.get("brandName").toString());
            //品牌英文 最福利没有
            supplierGoods.setBrandnameen(null);
            //TODO 一级分类暂时为空
            supplierGoods.setTypeId(null);
            supplierGoods.setTypeName(null);
            //二级分类 TODO
            supplierGoods.setCategoryParentId(null);
            supplierGoods.setCategoryParentName(null);
            //三级分类 TODO
            supplierGoods.setCategoryId(null);
            supplierGoods.setCategoryName(null);
            //产品详情格式类型 html , pic
            supplierGoods.setGoodsDescType("pic");
            // 这个字段 存储产品介绍详情，如果是图片不从这里取值 ，这里面只存富文本类型
            supplierGoods.setGoodsDesc(null);
            //供应商系统产品ID，用文本类型为了兼容不同供应商系统
            supplierGoods.setSupplierGoodsId(param.get("id").toString());
            //供应商ID
            Supplier supplier = new Supplier();
            supplier.setFullName("最福利");
            List<Supplier> suppliers = supplierService.queryAll(supplier);
            if(CollectionUtils.isEmpty(suppliers)){
                throw new BaseServiceException("当前产品查询不到对应的供应商["+supplier.getFullName()+"],产品id为:"+param.get("id"));
            }
            supplierGoods.setSupplierId(Integer.valueOf(suppliers.get(0).getId().toString()));
            //供应商名称
            supplierGoods.setSupplierName(suppliers.get(0).getFullName());
            //同步时间
            supplierGoods.setCreateTime(new Date());
            //最后更新时间
            supplierGoods.setLastUpdateTime(new Date());
            supplierGoods.setGoodNatureType(1);
            //规格描述 根据属性去拼接
            List<Map<String,Object>> skuVOs = JSONObject.parseObject(param.get("skuVOs").toString(), List.class);
            Map<String,List<String>> attr = new HashMap<>();
            for (Map<String,Object> sku:skuVOs) {
                String attributeName1 = sku.get("attributeName1").toString();
                if (attr.get(attributeName1) == null){
                    attr.put(attributeName1,new ArrayList<String>(){{
                        add(sku.get("attributeValue1").toString());
                    }});
                }else{
                    List<String> values = attr.get(attributeName1);
                    values.add(sku.get("attributeValue1").toString());
                    attr.put(attributeName1,values);
                }
                Object attributeName2 = sku.get("attributeName2");
                if (attributeName2 != null){
                    if (attr.get(attributeName2.toString()) == null){
                        attr.put(attributeName2.toString(),new ArrayList<String>(){{
                            add(sku.get("attributeValue2").toString());
                        }});
                    }else{
                        List<String> values = attr.get(attributeName2);
                        values.add(sku.get("attributeValue2").toString());
                        attr.put(attributeName2.toString(),values);
                    }
                }
            }
        List<Object> attrStr = new ArrayList<>();
        for (String key : attr.keySet()) {
            List<String> values = attr.get(key);
            List<Map<String,Object>> valueList = new ArrayList<>();
            for (String value:values) {
                valueList.add(new HashMap<String, Object>(){{
                    put("detailName",value);
                }});
            }
            Map<String,Object> attrMap = new HashMap<>();
            attrMap.put("name",key);
            attrMap.put("value",valueList);
            attrStr.add(attrMap);
        }
        supplierGoods.setSpecificationsString(JSONObject.toJSONString(attrStr));
        return supplierGoods;
    }


    public SupplierProduct packageObjectProduct(Map<String,Object> sku){
        SupplierProduct supplierProduct = new SupplierProduct();
        supplierProduct.setGid(Long.valueOf(sku.get("gid").toString()));
        //goodsId
        supplierProduct.setGoodsId(sku.get("goodsId").toString());
        //供应商SKU id
        supplierProduct.setProductId(sku.get("id").toString());
        //供应商SKU name
        if (sku.get("name") == null){
            supplierProduct.setProductName(sku.get("nameJd").toString());
        }else{
            supplierProduct.setProductName(sku.get("name").toString());
        }
        /**
         * SKU规格图片
         */
        supplierProduct.setProductImagePath(sku.get("image").toString());
        /**
         * 私有云图片地址
         */
        supplierProduct.setSelfProductImagePath(null);
        /**
         * SKU 条码
         */
        supplierProduct.setBarCode(null);
        /**
         * 是否含税 0 不含税  1 含税
         */
        supplierProduct.setHastax(0);
        /**
         *TODO  规格字符串JSON格式
         */
        List<Map<String,Object>> attrList = new ArrayList<>();
        attrList.add(new HashMap<String,Object>(){{
            put("specHeader",sku.get("attributeName1"));
            put("detailName",sku.get("attributeValue1"));
        }});
        if (sku.get("attributeName2") != null){
            if (StringUtils.isNotBlank(sku.get("attributeName2").toString())){
                attrList.add(new HashMap<String,Object>(){{
                    put("specHeader",sku.get("attributeName2"));
                    put("detailName",sku.get("attributeValue2"));
                }});
            }
        }

        supplierProduct.setSpecificationsString(JSONObject.toJSONString(attrList));
        /**
         * 0 : 不推送
         1 : 待推送
         2 : 已推送
         3 : 推送失败
         */
        supplierProduct.setPushStatus(Push.WAIT_DEAL.getName());
        /**
         * 是否进行图片压缩 0 未压缩 1 已经压缩
         * */
        supplierProduct.setIsImgCompression(ImageStatus.UNCOMPRESSED.getName());
        /**
         * 库存数,同步更新
         */
        supplierProduct.setInventoryNum(Integer.valueOf(sku.get("stockQuantity").toString()));
        return supplierProduct;
    }
    //获取hash值11
    public static int toHash(String key) {
        int arraySize = 11113; // 数组大小一般取质数
        int hashCode = 0;
        for (int i = 0; i < key.length(); i++) { // 从字符串的左边开始计算
            int letterValue = key.charAt(i) - 96;// 将获取到的字符串转换成数字，比如a的码值是97，则97-96=1
            // 就代表a的值，同理b=2；
            hashCode = ((hashCode << 5) + letterValue) % arraySize;// 防止编码溢出，对每步结果都进行取模运算
        }
        return hashCode;
    }

}
